<?php
// 课室信息展示页面 - 布局版
// 文件：/workspace/rooms_display.php

// 启用错误显示用于调试
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 启动会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户登录
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// 页面标题
$page_title = "课室整体布局";

// 数据库连接
require_once 'database.php';

// 数据库连接检查
$db_connected = true;
try {
    if (!$conn) {
        throw new Exception("数据库连接失败");
    }
    // 测试连接
    $conn->query("SELECT 1");
} catch (Exception $e) {
    error_log("数据库连接错误: " . $e->getMessage());
    $db_connected = false;
}

if (!$db_connected) {
    $_SESSION['error_message'] = "数据库连接失败，请联系管理员";
    header('Location: user_home.php');
    exit();
}

// 获取所有课室信息，按楼栋和楼层分组
$rooms_sql = "SELECT * FROM examination_rooms ORDER BY building_number DESC, floor_number, room_number";
$rooms_result = $conn->query($rooms_sql);

$rooms_by_building = [];
$total_rooms = 0;

if ($rooms_result) {
    while ($room = $rooms_result->fetch_assoc()) {
        // 使用building_number和floor_number字段进行分组
        $building = $room['building_number'] ?? 1;
        $floor = $room['floor_number'] ?? 1;

        if (!isset($rooms_by_building[$building])) {
            $rooms_by_building[$building] = [];
        }
        if (!isset($rooms_by_building[$building][$floor])) {
            $rooms_by_building[$building][$floor] = [];
        }

        $rooms_by_building[$building][$floor][] = $room;
        $total_rooms++;
    }
}

// 统计信息
$building_stats = [];
foreach ($rooms_by_building as $building => $floors) {
    $building_total = 0;
    foreach ($floors as $floor_rooms) {
        $building_total += count($floor_rooms);
    }
    $building_stats[$building] = $building_total;
}

// 获取课室背景色函数 - 更新版
function getRoomBackgroundColor($room) {
    $purpose = $room['purpose'] ?? '考场';
    $room_type = $room['room_type'] ?? '未分类';

    if ($purpose == '考点办公室') {
        return '#d65e88'; // 红色
    }

    if ($purpose == '空白') {
        return '#ffffff'; // 白色
    }

    if ($purpose == '考场') {
        if ($room_type == '学生课室') {
            return '#0d6efd'; // 蓝色
        }
        if ($room_type == '实训室') {
            return '#ffc107'; // 黄色
        }
        if ($room_type == '电脑机房') {
            return '#198754'; // 绿色
        }
    }

    return '#808080'; // 灰色 - 其他情况
}

// 课室排列函数
function arrangeRoomsForFloor($rooms, $building_number) {
    $arranged = [];

    if (in_array($building_number, [1, 4, 5, 6, 7])) {
        // 1号楼、4号楼、5号楼、6号楼、7号楼：从右到左按room_number末尾最后一位数字递增排列
        usort($rooms, function($a, $b) {
            $lastDigitA = intval(substr($a['room_number'], -2, 1)); // 倒数第二位
            $lastDigitB = intval(substr($b['room_number'], -2, 1));
            return $lastDigitA - $lastDigitB;
        });
        $arranged = array_reverse($rooms);
    }
    elseif (in_array($building_number, [2, 3])) {
        // 2号楼及3号楼：区分主楼与辅楼
        $main_building = [];
        $aux_building = [];

        foreach ($rooms as $room) {
            if (isset($room['sub_building']) && $room['sub_building'] === '辅楼') {
                $aux_building[] = $room;
            } else {
                $main_building[] = $room;
            }
        }

        // 各自排序：从右到左按末尾数字递增
        usort($aux_building, function($a, $b) {
            $lastDigitA = intval(substr($a['room_number'], -2, 1));
            $lastDigitB = intval(substr($b['room_number'], -2, 1));
            return $lastDigitA - $lastDigitB;
        });
        $aux_building = array_reverse($aux_building);

        usort($main_building, function($a, $b) {
            $lastDigitA = intval(substr($a['room_number'], -2, 1));
            $lastDigitB = intval(substr($b['room_number'], -2, 1));
            return $lastDigitA - $lastDigitB;
        });
        $main_building = array_reverse($main_building);

        $arranged = [
            'aux' => $aux_building,
            'main' => $main_building
        ];
    }
    elseif ($building_number == 8) {
        // 8号楼：区分A座与B座 - 修复版
        $a_building = [];
        $b_building = [];

        foreach ($rooms as $room) {
            if (isset($room['sub_building']) && $room['sub_building'] === 'B') {
                $b_building[] = $room;
            } elseif (isset($room['sub_building']) && $room['sub_building'] === 'A') {
                $a_building[] = $room;
            } else {
                // 如果没有明确标记，默认归类为A座
                $a_building[] = $room;
            }
        }

        // A座和B座各自从左到右按末尾数字递增
        usort($a_building, function($a, $b) {
            $lastDigitA = intval(substr($a['room_number'], -2, 1));
            $lastDigitB = intval(substr($b['room_number'], -2, 1));
            return $lastDigitA - $lastDigitB;
        });

        usort($b_building, function($a, $b) {
            $lastDigitA = intval(substr($a['room_number'], -2, 1));
            $lastDigitB = intval(substr($b['room_number'], -2, 1));
            return $lastDigitA - $lastDigitB;
        });

        $arranged = [
            'a' => $a_building,
            'b' => $b_building
        ];
    }
    else {
        // 其他楼栋：简单排序
        usort($rooms, function($a, $b) {
            return strcmp($a['room_number'], $b['room_number']);
        });
        $arranged = $rooms;
    }

    return $arranged;
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- 统一样式 -->
    <link rel="stylesheet" href="css/unified-style.css">

    <style>
        .building-section {
            margin-bottom: 40px;
        }

        .building-title {
            color: #1f2937;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #0d6efd;
        }

        .floor-table {
            width: 100%;
            border: 2px solid #0d6efd;
            border-collapse: collapse;
            margin-bottom: 20px;
            background: white;
            table-layout: fixed;
        }

        .floor-table th,
        .floor-table td {
            border: 1px solid #dee2e6;
            padding: 8px;
            text-align: center;
            vertical-align: middle;
        }

        .floor-table th {
            background: #0d6efd;
            color: white;
            font-weight: 600;
        }

        .room-cell {
            border: 1px solid #dee2e6;
            padding: 10px;
            font-weight: 600;
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .room-cell:hover {
            opacity: 0.8;
            transform: scale(1.05);
        }

        .separator-cell {
            background: #e9ecef;
            color: #6c757d;
            font-size: 10px;
            width: 60px;
            padding: 5px 2px;
            border: 1px solid #ced4da;
        }

        .floor-label {
            background: #ffffff !important;
            color: #000000 !important;
            font-weight: 600;
            width: 80px;
        }

        .enhancement-notice {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            color: #856404;
        }

        .enhancement-notice .badge {
            background: #ffc107;
            color: #212529;
            margin-right: 5px;
        }

        .empty-cell {
            background: #ffffff;
            border: 1px solid #e9ecef;
            padding: 10px;
        }

        /* 颜色说明 */
        .color-legend {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .color-item {
            display: inline-block;
            margin-right: 20px;
            margin-bottom: 5px;
        }

        .color-box {
            display: inline-block;
            width: 20px;
            height: 20px;
            margin-right: 5px;
            vertical-align: middle;
            border: 1px solid #dee2e6;
        }
    </style>
</head>
<body>
<!-- 导航栏 -->
<?php include_once 'common/navigation.php'; ?>

<!-- 主要内容 -->
<div class="container-fluid main-content">
    <!-- 页面标题 -->
    <div class="card">
        <div class="page-header">
            <h1 class="page-title">课室整体布局 - 更新版</h1>
            <p class="page-subtitle">按实际物理布局展示各楼栋课室分布，已更新颜色逻辑和空白课室处理</p>
        </div>
    </div>

    <!-- 功能增强通知 -->
    <div class="enhancement-notice">
        <h6><i class="fas fa-palette"></i> 颜色逻辑更新</h6>
        <p class="mb-0">
            <span class="badge">UPDATED</span>
            已更新课室颜色逻辑，支持考点办公室、空白课室等新类型。空白课室不显示课室号。
        </p>
    </div>

    <!-- 颜色说明 - 更新版 -->
    <div class="color-legend">
        <h6><i class="fas fa-palette"></i> 课室类型颜色说明</h6>
        <div class="color-item">
            <span class="color-box" style="background-color: #d65e88;"></span>
            <span>红色：考点办公室</span>
        </div>
        <div class="color-item">
            <span class="color-box" style="background-color: #ffffff; border: 2px solid #000;"></span>
            <span>白色：空白</span>
        </div>
        <div class="color-item">
            <span class="color-box" style="background-color: #0d6efd;"></span>
            <span>蓝色：学生课室</span>
        </div>
        <div class="color-item">
            <span class="color-box" style="background-color: #ffc107;"></span>
            <span>黄色：实训室</span>
        </div>
        <div class="color-item">
            <span class="color-box" style="background-color: #198754;"></span>
            <span>绿色：电脑机房</span>
        </div>
        <div class="color-item">
            <span class="color-box" style="background-color: #808080;"></span>
            <span>灰色：其他类型</span>
        </div>
    </div>

    <!-- 统计概览 -->
    <div class="card">
        <div class="card-header">
            <i class="fas fa-chart-bar"></i> 课室统计概览
            <div class="d-flex gap-2 ms-auto">
                <a href="rooms_display_detail.php" class="btn btn-success">
                    <i class="fas fa-list-ul"></i> 显示课室详细信息
                </a>
                <a href="add_room.php" class="btn btn-warning">
                    <i class="fas fa-plus"></i> 添加新课室
                </a>
            </div>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3">
                    <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-building text-primary"></i> 总课室数
                            </span>
                        <span class="info-value"><?php echo $total_rooms; ?></span>
                    </div>
                </div>
                <?php foreach ($building_stats as $building => $count): ?>
                    <div class="col-md-3">
                        <div class="info-item">
                                <span class="info-label">
                                    <i class="fas fa-home text-info"></i> <?php echo $building; ?>号楼
                                </span>
                            <span class="info-value"><?php echo $count; ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- 课室布局展示 -->
    <?php if (!empty($rooms_by_building)): ?>
        <?php foreach ($rooms_by_building as $building => $floors): ?>
            <div class="building-section">
                <h2 class="building-title">
                    <i class="fas fa-building"></i> <?php echo $building; ?>号楼
                    <small class="text-muted">(<?php echo $building_stats[$building]; ?>间课室)</small>
                </h2>

                <table class="floor-table">
                    <?php
                    // 高楼层在上方，低楼层在下方
                    krsort($floors);
                    foreach ($floors as $floor => $floor_rooms):
                        $arranged_rooms = arrangeRoomsForFloor($floor_rooms, $building);
                        ?>
                        <tr>
                            <?php if (in_array($building, [2, 3])): ?>
                                <!-- 2号楼和3号楼：辅楼 → 厕所楼梯 → 主楼3&4室 → 楼梯通道 → 主楼1&2室 → 楼层标识 -->
                                <?php
                                $aux_rooms = isset($arranged_rooms['aux']) ? $arranged_rooms['aux'] : [];
                                $main_rooms = isset($arranged_rooms['main']) ? $arranged_rooms['main'] : [];

                                // 辅楼区域
                                foreach ($aux_rooms as $room): ?>
                                    <td class="room-cell" style="background-color: <?php echo getRoomBackgroundColor($room); ?>;" onclick="editRoom(<?php echo $room['id']; ?>)">
                                        <?php
                                        if ($room['purpose'] == '空白') {
                                            echo '';
                                        } else {
                                            echo htmlspecialchars($room['room_number']);
                                        }
                                        ?>
                                    </td>
                                <?php endforeach; ?>

                                <!-- 厕所楼梯分隔符 -->
                                <td class="separator-cell">厕所<br>楼梯</td>

                                <!-- 主楼3&4室 -->
                                <?php
                                $main_34_rooms = array_slice($main_rooms, 0, 2); // 取第3、4个房间
                                foreach ($main_34_rooms as $room): ?>
                                    <td class="room-cell" style="background-color: <?php echo getRoomBackgroundColor($room); ?>;" onclick="editRoom(<?php echo $room['id']; ?>)">
                                        <?php
                                        if ($room['purpose'] == '空白') {
                                            echo '';
                                        } else {
                                            echo htmlspecialchars($room['room_number']);
                                        }
                                        ?>
                                    </td>
                                <?php endforeach; ?>

                                <!-- 楼梯通道分隔符 -->
                                <td class="separator-cell">楼梯<br>通道</td>

                                <!-- 主楼1&2室 -->
                                <?php
                                $main_12_rooms = array_slice($main_rooms, 2, 2); // 取第1、2个房间
                                foreach ($main_12_rooms as $room): ?>
                                    <td class="room-cell" style="background-color: <?php echo getRoomBackgroundColor($room); ?>;" onclick="editRoom(<?php echo $room['id']; ?>)">
                                        <?php
                                        if ($room['purpose'] == '空白') {
                                            echo '';
                                        } else {
                                            echo htmlspecialchars($room['room_number']);
                                        }
                                        ?>
                                    </td>
                                <?php endforeach; ?>

                            <?php elseif ($building == 8): ?>
                                <!-- 8号楼：B座课室 → 连廊楼梯 → A座课室 → 楼层标识 -->

                                <!-- B座课室 -->
                                <?php if (!empty($arranged_rooms['b'])): ?>
                                    <?php foreach ($arranged_rooms['b'] as $room): ?>
                                        <td class="room-cell" style="background-color: <?php echo getRoomBackgroundColor($room); ?>;" onclick="editRoom(<?php echo $room['id']; ?>)">
                                            <?php
                                            if ($room['purpose'] == '空白') {
                                                echo '';
                                            } else {
                                                echo htmlspecialchars($room['room_number']);
                                            }
                                            ?>
                                        </td>
                                    <?php endforeach; ?>
                                <?php endif; ?>

                                <!-- 连廊楼梯分隔符 -->
                                <td class="separator-cell">连廊<br>楼梯</td>

                                <!-- A座课室 -->
                                <?php if (!empty($arranged_rooms['a'])): ?>
                                    <?php foreach ($arranged_rooms['a'] as $room): ?>
                                        <td class="room-cell" style="background-color: <?php echo getRoomBackgroundColor($room); ?>;" onclick="editRoom(<?php echo $room['id']; ?>)">
                                            <?php
                                            if ($room['purpose'] == '空白') {
                                                echo '';
                                            } else {
                                                echo htmlspecialchars($room['room_number']);
                                            }
                                            ?>
                                        </td>
                                    <?php endforeach; ?>
                                <?php endif; ?>

                            <?php else: ?>
                                <!-- 1号楼、4号楼、7号楼等：课室/楼层标识 -->
                                <?php if (is_array($arranged_rooms)): ?>
                                    <?php foreach ($arranged_rooms as $room): ?>
                                        <td class="room-cell" style="background-color: <?php echo getRoomBackgroundColor($room); ?>;" onclick="editRoom(<?php echo $room['id']; ?>)">
                                            <?php
                                            if ($room['purpose'] == '空白') {
                                                echo '';
                                            } else {
                                                echo htmlspecialchars($room['room_number']);
                                            }
                                            ?>
                                        </td>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            <?php endif; ?>

                            <!-- 楼层标识 -->
                            <td class="floor-label">
                                <?php
                                if ($floor == -1) {
                                    echo 'B1';
                                } else {
                                    echo $floor . 'F';
                                }
                                ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="card">
            <div class="card-body">
                <div class="text-center py-5">
                    <div class="mb-3">
                        <i class="fas fa-building" style="font-size: 48px; color: #6c757d;"></i>
                    </div>
                    <h4 class="text-muted">暂无课室信息</h4>
                    <p class="text-muted">还没有添加任何课室</p>
                    <a href="add_room.php" class="btn btn-warning">
                        <i class="fas fa-plus"></i> 添加第一个课室
                    </a>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // 编辑课室
    function editRoom(roomId) {
        window.location.href = 'edit_room.php?id=' + roomId;
    }

    // 页面加载动画
    document.addEventListener('DOMContentLoaded', function() {
        const tables = document.querySelectorAll('.floor-table');

        tables.forEach((table, index) => {
            table.style.opacity = '0';
            table.style.transform = 'translateY(20px)';

            setTimeout(() => {
                table.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                table.style.opacity = '1';
                table.style.transform = 'translateY(0)';
            }, index * 200);
        });
    });
</script>

<?php
// 关闭数据库连接
if (isset($conn)) {
    $conn->close();
}
?>
</body>
</html>